package com.baibei.widget;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.LoadingMoreFooter;
import com.jcodecraeer.xrecyclerview.progressindicator.AVLoadingIndicatorView;
import com.jcodecraeer.xrecyclerview.progressindicator.indicator.BaseIndicatorController;

import java.lang.reflect.Field;

/**
 * 加载更多
 * Created by ChenRui on 2016/12/3 17:56.
 */
public class RaeLoadMoreView extends LoadingMoreFooter {

    private TextView mTextView;
    private String mNoMoreText;
    private ViewGroup mProgressBarLayout;
    private int mTextColor;

    public RaeLoadMoreView(Context context) {
        this(context, null);
    }

    public RaeLoadMoreView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setPadding(0, 32, 0, 32);
    }

    @Override
    public void initView() {
        super.initView();
        mTextColor = Color.parseColor("#292931");
        mProgressBarLayout = (ViewGroup) getChildAt(0);
        mTextView = (TextView) getChildAt(1);
        mNoMoreText = getResources().getString(R.string.nomore_loading);
    }

    public void setNoMoreText(String text) {
        mNoMoreText = text;
    }


    public void setTextSize(int size) {
        mTextView.setTextSize(size);
    }

    public void setProgressBarSize(int width, int height) {
        mProgressBarLayout.getLayoutParams().width = width;
        mProgressBarLayout.getLayoutParams().height = height;
    }

    @Override
    public void setState(int state) {
        if (state == STATE_NOMORE) {
            mTextView.setText(mNoMoreText);
            mProgressBarLayout.setVisibility(View.GONE);
            mTextView.setTextColor(getResources().getColor(R.color.dividerColor));
            this.setVisibility(View.VISIBLE);
            return;
        } else {
            mTextView.setTextColor(mTextColor);
        }
        super.setState(state);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    public void removeAllViews() {
        try {
            // 解决内存溢出
            AVLoadingIndicatorView loadingView = (AVLoadingIndicatorView) mProgressBarLayout.getChildAt(0);
            if (loadingView != null) {
                // 反射获取 mIndicatorController
                Field field = loadingView.getClass().getDeclaredField("mIndicatorController");
                field.setAccessible(true);
                BaseIndicatorController controller = (BaseIndicatorController) field.get(loadingView);
                controller.setTarget(null);
            }
            mProgressBarLayout.removeAllViews();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.removeAllViews();
    }
}
